<script lang="ts" setup>
import { ref, onMounted, reactive, watch, computed, nextTick } from "vue";
import { useRouter } from "vue-router";
import { Search, Right, Loading, Delete, Location, Calendar, Briefcase } from "@element-plus/icons-vue";
import headerIndex from "./components/headerIndex.vue";
import footerIndex from "./components/footerIndex.vue";
// @ts-ignore
import PositionFilter from "./components/PositionFilter.vue";
// @ts-ignore
import PositionCard from "./components/PositionCard.vue";
// @ts-ignore
import PositionDetail from "./components/PositionDetail.vue";

const router = useRouter();

// 搜索相关
const searchKeyword = ref("");
const searchHistory = ref<string[]>([]);
const searchType = ref("position");
const searchTypeOptions = [
    { label: "职位", value: "position" },
    { label: "公司", value: "company" },
    { label: "技能", value: "skill" },
];
const hotSearchTags = ref(["前端开发", "Java", "产品经理", "UI设计", "人工智能"]);
const searchFocus = ref(false);
const sortType = ref("latest");

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const totalPositions = ref(100);
const noMore = ref(false);
const loading = ref(false);

// 判断是否禁用加载
const disabled = computed(() => loading.value || noMore.value);

// 选中的职位ID
const selectedPositionId = ref<string | null>(null);

// 筛选条件
const filterConditions = reactive<any>({
    categories: [],
    salary: "all",
    experience: ["all"],
    education: ["all"],
    companySize: ["all"],
});

// 统一的公司logo URL
const companyLogoUrl =
    "https://img.bosszhipin.com/beijin/mcs/banner/71f4ee09b9a2abfb675b5c705fc46c9dcfcd208495d565ef66e7dff9f98764da.jpg?x-oss-process=image/resize,w_100,limit_0";

// 职位列表数据
const positionList = ref<any[]>([
    {
        id: "1",
        title: "前端开发工程师",
        salary: "5-6K",
        tags: ["经验不限", "学历不限", "全职"],
        companyName: "中科联核",
        companyLogo: companyLogoUrl,
        location: "天津 西青区 保税区",
    },
    {
        id: "2",
        title: "前端开发工程师",
        salary: "8-12K",
        tags: ["1-3年", "本科", "全职"],
        companyName: "中科联信",
        companyLogo: companyLogoUrl,
        location: "天津 滨海新区 开发区",
    },
    {
        id: "3",
        title: "前端开发工程师(联想 天津)",
        salary: "14-15K",
        tags: ["5-10年", "本科", "全职"],
        companyName: "得物信息",
        companyLogo: companyLogoUrl,
        location: "天津 东丽区 46街",
    },
    {
        id: "4",
        title: "web前端开发工程师",
        salary: "8-12K",
        tags: ["1-3年", "本科", "全职"],
        companyName: "它思科技",
        companyLogo: companyLogoUrl,
        location: "天津 滨海新区 中新生态城",
    },
    {
        id: "5",
        title: "前端开发工程师",
        salary: "11-14K",
        tags: ["5-10年", "本科", "全职"],
        companyName: "牛教科技",
        companyLogo: companyLogoUrl,
        location: "天津",
    },
]);

// 操作搜索历史记录
const saveSearchHistory = () => {
    try {
        localStorage.setItem("searchHistory", JSON.stringify(searchHistory.value));
    } catch (e) {
        console.error("保存搜索历史失败", e);
    }
};

// 处理搜索
const handleSearch = () => {
    if (!searchKeyword.value.trim()) return;

    // 保存到搜索历史
    if (!searchHistory.value.includes(searchKeyword.value)) {
        searchHistory.value.unshift(searchKeyword.value);
        // 只保留最近10条
        if (searchHistory.value.length > 10) {
            searchHistory.value = searchHistory.value.slice(0, 10);
        }
        saveSearchHistory();
    }

    currentPage.value = 1;
    fetchPositionList();
    searchFocus.value = false;
};

// 清空搜索框
const clearSearch = () => {
    searchKeyword.value = "";
};

// 清除全部历史记录
const clearAllHistory = () => {
    searchHistory.value = [];
    localStorage.removeItem("searchHistory");
};

// 移除单条历史记录
const removeHistory = (index: number) => {
    searchHistory.value.splice(index, 1);
    saveSearchHistory();
};

// 选择历史记录或热门标签
const selectSearchItem = (text: string) => {
    searchKeyword.value = text;
    handleSearch();
};

// 处理筛选条件变化
const handleFilterChange = (filters: any) => {
    currentPage.value = 1;
    fetchPositionList();
};

// 处理排序方式变化
const handleSortChange = () => {
    currentPage.value = 1;
    fetchPositionList();
};

// 处理分页变化
const handlePageChange = (page: number) => {
    currentPage.value = page;
    fetchPositionList();
};

// 查看职位详情 - 只显示详情不跳转
const viewPositionDetail = (positionId: string) => {
    selectedPositionId.value = positionId;
};

// 跳转到职位详情页面
const goToPositionInfo = (id: string) => {
    router.push({
        path: "/jobInfo",
        query: { id },
    });
};

// 跳转到公司详情页面
const goToCompanyInfo = (companyName: string) => {
    // 这里应该使用公司ID，这里为了演示使用公司名称
    router.push({
        path: "/companyInfo",
        query: { id: companyName === "中科联核" ? "1" : companyName === "中科联信" ? "2" : "3" },
    });
};

// 获取职位列表数据
const fetchPositionList = () => {
    loading.value = true;

    // 这里应该根据searchType, searchKeyword和filterConditions构建API请求参数
    const params = {
        keyword: searchKeyword.value,
        searchType: searchType.value,
        page: currentPage.value,
        pageSize: pageSize.value,
        ...filterConditions,
    };

    // 模拟API请求延迟
    setTimeout(() => {
        // TODO: 实际项目中这里应该调用API
        // const result = await api.getPositionList(params);
        // positionList.value = result.data;
        // totalPositions.value = result.total;

        loading.value = false;
    }, 500);
};

// 加载更多数据
const loadMore = () => {
    if (loading.value || noMore.value) return;
    loading.value = true;

    // 模拟API请求延迟
    setTimeout(() => {
        // 这里应该是实际的API调用
        const newPositions = [
            {
                id: String(positionList.value.length + 1),
                title: "前端开发工程师",
                salary: "15-20K",
                tags: ["3-5年", "本科", "全职"],
                companyName: "新公司" + (positionList.value.length + 1),
                companyLogo: companyLogoUrl,
                location: "天津",
            },
            {
                id: String(positionList.value.length + 2),
                title: "高级前端工程师",
                salary: "25-35K",
                tags: ["5-10年", "本科", "全职"],
                companyName: "新公司" + (positionList.value.length + 2),
                companyLogo: companyLogoUrl,
                location: "天津",
            },
        ];

        // 模拟数据到达上限的情况
        if (positionList.value.length >= 30) {
            noMore.value = true;
        } else {
            positionList.value.push(...newPositions);
        }

        loading.value = false;
    }, 800);
};

// 监听路由参数变化
watch(
    () => router.currentRoute.value.query,
    (newQuery: any) => {
        if (newQuery.keyword && typeof newQuery.keyword === "string") {
            searchKeyword.value = newQuery.keyword;
        }
        fetchPositionList();
    },
    { immediate: true }
);

// 处理搜索框失焦延迟
const handleSearchBlur = () => {
    nextTick(() => {
        setTimeout(() => {
            searchFocus.value = false;
        }, 200);
    });
};

// 监听搜索类型变化，更新placeholder
watch(searchType, () => {
    if (searchFocus.value) {
        searchFocus.value = false;
        setTimeout(() => {
            searchFocus.value = true;
        }, 50);
    }
});

onMounted(() => {
    // 从本地存储获取搜索历史
    try {
        const savedHistory = localStorage.getItem("searchHistory");
        if (savedHistory) {
            searchHistory.value = JSON.parse(savedHistory);
        }
    } catch (e) {
        console.error("获取搜索历史失败", e);
    }

    fetchPositionList();
    // 默认选中第一个职位
    if (positionList.value.length > 0) {
        selectedPositionId.value = positionList.value[0].id;
    }
});
</script>

<template>
    <div class="position-page">
        <headerIndex></headerIndex>
        <el-container>
            <el-main>
                <!-- 主内容区域 -->
                <el-row justify="center">
                    <!-- 搜索框模块 - 简洁设计 -->
                    <el-col :span="24" class="search-wrapper">
                        <div class="search-container">
                            <el-input
                                v-model="searchKeyword"
                                placeholder="搜索职位、公司"
                                class="search-input-simple"
                                @keyup.enter="handleSearch"
                                @focus="searchFocus = true"
                                @blur="handleSearchBlur"
                                clearable
                            >
                                <template #prefix>
                                    <el-icon class="search-icon"><Search /></el-icon>
                                </template>
                                <template #suffix>
                                    <el-button class="search-btn" type="primary" @click="handleSearch">
                                        搜索
                                    </el-button>
                                </template>
                            </el-input>

                            <!-- 搜索下拉面板 -->
                            <div
                                class="search-dropdown"
                                v-show="searchFocus && (searchHistory.length > 0 || hotSearchTags.length > 0)"
                            >
                                <!-- 历史搜索 -->
                                <div class="search-history" v-if="searchHistory.length > 0">
                                    <div class="search-dropdown-header">
                                        <h4>历史搜索</h4>
                                        <el-button type="text" size="small" @click="clearAllHistory">清除</el-button>
                                    </div>
                                    <ul class="history-list">
                                        <li
                                            v-for="(item, index) in searchHistory.slice(0, 5)"
                                            :key="index"
                                            class="history-item"
                                            @click="selectSearchItem(item)"
                                        >
                                            <el-icon><Calendar /></el-icon>
                                            <span>{{ item }}</span>
                                            <el-button
                                                class="delete-btn"
                                                type="text"
                                                @click.stop="removeHistory(index)"
                                            >
                                                <el-icon><Delete /></el-icon>
                                            </el-button>
                                        </li>
                                    </ul>
                                </div>

                                <!-- 热门搜索 -->
                                <div class="hot-search" v-if="hotSearchTags.length > 0">
                                    <div class="search-dropdown-header">
                                        <h4>热门搜索</h4>
                                    </div>
                                    <div class="hot-tags">
                                        <el-tag
                                            v-for="(tag, index) in hotSearchTags"
                                            :key="index"
                                            :effect="searchKeyword === tag ? 'dark' : 'plain'"
                                            @click="selectSearchItem(tag)"
                                            class="hot-tag"
                                            size="small"
                                        >
                                            {{ tag }}
                                        </el-tag>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-col>

                    <!-- 筛选条件 -->
                    <el-col :span="24" class="filter-wrapper">
                        <PositionFilter @filter-change="handleFilterChange"></PositionFilter>
                    </el-col>

                    <!-- 主内容区：左侧职位列表 + 右侧职位详情 -->
                    <el-col :span="24" class="main-content">
                        <!-- 左侧职位列表 -->
                        <div class="position-list-container">
                            <div
                                class="position-list"
                                v-infinite-scroll="loadMore"
                                :infinite-scroll-disabled="disabled"
                                :infinite-scroll-delay="500"
                                :infinite-scroll-distance="10"
                                :infinite-scroll-immediate="true"
                            >
                                <PositionCard
                                    v-for="item in positionList"
                                    :key="item.id"
                                    :position-data="item"
                                    :is-active="selectedPositionId === item.id"
                                    @click="viewPositionDetail(item.id)"
                                    @company-click="goToCompanyInfo(item.companyName)"
                                ></PositionCard>

                                <!-- 加载状态 -->
                                <div v-if="loading" class="loading-status">
                                    <el-icon class="loading-icon"><Loading /></el-icon>
                                    <span>加载中...</span>
                                </div>

                                <!-- 无更多数据提示 -->
                                <div v-if="noMore" class="no-more-status">
                                    <el-divider>
                                        <span class="no-more-text">已经到底啦 ~</span>
                                    </el-divider>
                                </div>

                                <!-- 无数据提示 -->
                                <el-empty v-if="positionList.length === 0 && !loading" description="暂无符合条件的职位">
                                </el-empty>
                            </div>
                        </div>

                        <!-- 右侧职位详情 -->
                        <div class="position-detail-container">
                            <PositionDetail :position-id="selectedPositionId"></PositionDetail>
                        </div>
                    </el-col>
                </el-row>
            </el-main>
        </el-container>
        <footerIndex></footerIndex>
        <el-backtop :bottom="80" target=".position-page" />
    </div>
</template>

<style scoped>
.position-page {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    overflow-x: hidden;
}

.el-main {
    --el-main-padding: 0;
    background-color: transparent;
}

/* 搜索框容器 - 无背景 */
.search-wrapper {
    margin: 28px 0 20px;
    padding: 0;
    position: relative;
    background-color: transparent;
}

.search-container {
    max-width: 650px;
    margin: 0 auto;
    padding: 0 15px;
    position: relative;
}

/* 搜索输入框 */
.search-input-simple {
    width: 100%;
    --el-input-height: 44px;
}

/* 输入框样式 */
:deep(.search-input-simple .el-input__wrapper) {
    border-radius: 22px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    padding-right: 110px; /* 为按钮留出空间 */
    transition: all 0.3s ease;
}

:deep(.search-input-simple .el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.search-input-simple .el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.search-input-simple .el-input__inner) {
    color: #333;
    font-size: 14px;
}

/* 搜索图标 */
.search-icon {
    font-size: 16px;
    color: #909399;
    margin-right: 6px;
}

/* 搜索按钮 */
.search-btn {
    height: 32px;
    border-radius: 16px;
    padding: 0 20px;
    position: absolute;
    right: 6px;
    top: 50%;
    transform: translateY(-50%);
    background-color: #1989fa;
    border-color: #1989fa;
    font-size: 14px;
    font-weight: normal;
    z-index: 10;
}

.search-btn:hover,
.search-btn:focus {
    background-color: #409eff;
    border-color: #409eff;
}

/* 下拉搜索面板 */
.search-dropdown {
    position: absolute;
    top: 100%;
    left: 15px;
    right: 15px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 100;
    padding: 12px;
    margin-top: 8px;
    max-height: 300px;
    overflow-y: auto;
}

/* 历史搜索 */
.search-dropdown-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.search-dropdown-header h4 {
    margin: 0;
    font-size: 13px;
    color: #909399;
    font-weight: 500;
}

.search-history {
    margin-bottom: 10px;
}

.history-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.history-item {
    display: flex;
    align-items: center;
    padding: 6px 8px;
    cursor: pointer;
    color: #606266;
    transition: all 0.2s;
    font-size: 13px;
    border-radius: 3px;
}

.history-item:hover {
    color: #409eff;
    background-color: #f5f7fa;
}

.history-item .el-icon {
    margin-right: 6px;
    font-size: 14px;
    color: #909399;
}

.history-item span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.delete-btn {
    opacity: 0;
    transition: all 0.2s;
    color: #c0c4cc;
    padding: 2px;
}

.history-item:hover .delete-btn {
    opacity: 1;
}

.delete-btn:hover {
    color: #f56c6c;
}

/* 热门搜索 */
.hot-search {
    margin-bottom: 5px;
}

.hot-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.hot-tag {
    cursor: pointer;
    margin-right: 0;
    transition: all 0.2s;
}

.hot-tag:hover {
    color: #409eff;
    border-color: #409eff;
}

/* 移动端响应式 */
@media (max-width: 768px) {
    .search-container {
        padding: 0 10px;
    }

    .search-dropdown {
        left: 10px;
        right: 10px;
    }

    .search-btn {
        padding: 0 15px;
    }
}

/* 主内容区域样式 */
.main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px 20px;
    display: flex;
    gap: 20px;
}

/* 筛选条件包装器 */
.filter-wrapper {
    max-width: 1200px;
    margin: 0 auto 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

/* 职位列表容器 */
.position-list-container {
    width: 100%;
    max-width: 420px;
    flex-shrink: 0;
}

.position-list {
    background: #fff;
    border-radius: 8px;
    height: calc(100vh - 120px);
    overflow-y: auto;
    padding: 8px;
    scrollbar-width: none; /* Firefox */
    &::-webkit-scrollbar {
        display: none;
    }
}

/* 骨架屏样式 */
.skeleton-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 16px;
    display: flex;
    gap: 16px;
    border: 1px solid #e4e7ed;
}

/* 职位详情容器 */
.position-detail-container {
    flex: 1;
    min-width: 0;
    background: #fff;
    border-radius: 8px;
    border: none;
    padding: 24px;
    position: sticky;
    top: 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    scrollbar-width: none; /* Firefox */
    &::-webkit-scrollbar {
        display: none;
    }
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin: 24px 0;
}

/* 桌面端响应式样式 */
@media (min-width: 768px) {
    .position-detail-container {
        margin-left: 20px;
    }
}

/* 移动端响应式样式 */
@media (max-width: 992px) {
    .main-content {
        flex-direction: column;
        gap: 15px;
    }
    .position-list-container {
        max-width: 100%;
    }
    .position-detail-container {
        position: static;
        height: auto;
        max-height: none;
        margin-top: 0;
    }
}

@media (max-width: 768px) {
    .location-btn {
        padding: 0 10px;
    }

    .search-btn-redesign {
        padding: 0 16px;
    }

    :deep(.search-input-redesign .el-input__inner) {
        font-size: 14px;
    }

    .search-dropdown-redesign {
        left: 10px;
        right: 10px;
    }
}

/* 加载状态样式 */
.loading-status {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px 0;
    color: #909399;
    font-size: 14px;
}

.loading-icon {
    animation: rotating 1.5s linear infinite;
    margin-right: 8px;
    font-size: 16px;
}

.no-more-status {
    padding: 15px 0;
}

.no-more-text {
    color: #909399;
    font-size: 14px;
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
